package hot100;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class Solution145 {
    List<Integer> list = new LinkedList<>();
    public List<Integer> postorderTraversal1(TreeNode root) {
        dfs(root);
        return list;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        dfs(root.right);
        list.add(root.val);
    }

    Deque<TreeNode> stack = new LinkedList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            TreeNode right = root.right;
            while (right != null) {
                stack.push(right);
                right = right.right;
            }
            list.add(root.val);
        }
        return list;
    }

    private void morris(TreeNode root) {
        while (root != null) {
            if (root.left == null) {
                list.add(root.val);
                root = root.right;
            } else {
                TreeNode predecessor = root.left;
                while(predecessor.right != null && predecessor.right != root) {
                    predecessor = predecessor.right;
                }
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                } else {
                    list.add(root.val);
                    root = predecessor.right;
                }
            }
        }
    }

    private TreeNode getPredecessor(TreeNode node) {
        TreeNode predecessor = node.left;
        while (predecessor.right != null) {
            predecessor = predecessor.right;
        }
        return predecessor;
    }

}
